﻿using System;
using System.Collections.Generic;
using System.Linq;
using Authy.Net;
using Microsoft.WindowsAzure.Storage;
using Microsoft.WindowsAzure.Storage.Table;
using Microsoft.AspNet.Membership.OpenAuth;

namespace MFAAuthyTest.Account
{
    public partial class Manage : System.Web.UI.Page
    {
        protected string SuccessMessage
        {
            get;
            private set;
        }

        protected bool CanRemoveExternalLogins
        {
            get;
            private set;
        }

        protected void Page_Load()
        {
            if (!IsPostBack)
            {
                // Determine the sections to render
                var hasLocalPassword = OpenAuth.HasLocalPassword(User.Identity.Name);
                //setPassword.Visible = !hasLocalPassword;
                //changePassword.Visible = hasLocalPassword;

                //CanRemoveExternalLogins = hasLocalPassword;

                //// Render success message
                //var message = Request.QueryString["m"];
                //if (message != null)
                //{
                //    // Strip the query string from action
                //    Form.Action = ResolveUrl("~/Account/Manage");

                //    SuccessMessage =
                //        message == "ChangePwdSuccess" ? "Your password has been changed."
                //        : message == "SetPwdSuccess" ? "Your password has been set."
                //        : message == "RemoveLoginSuccess" ? "The external login was removed."
                //        : String.Empty;
                //    successMessage.Visible = !String.IsNullOrEmpty(SuccessMessage);
                //}
            }

        }

        //protected void setPassword_Click(object sender, EventArgs e)
        //{
        //    if (IsValid)
        //    {
        //        var result = OpenAuth.AddLocalPassword(User.Identity.Name, password.Text);
        //        if (result.IsSuccessful)
        //        {
        //            Response.Redirect("~/Account/Manage?m=SetPwdSuccess");
        //        }
        //        else
        //        {

        //            ModelState.AddModelError("NewPassword", result.ErrorMessage);

        //        }
        //    }
        //}

        protected void validateToken_Click(object sender, EventArgs e)
        {
           
            if (IsValid)
            {
                AuthyClient client = new AuthyClient("9d757c049978d32651d0e11e801b36f2", test: false);

                // for a real storage account:
                String dataConnectionString = "DefaultEndpointsProtocol=https;AccountName=aliciaauthy;AccountKey=UihKsy9AYk9R/UFMhpnxs9Ju459H+BVaUROJ5SJuGL7M2y8ILV8QwmeEK1gw+ga+AYwcF9nMjq5VPsztoGHT1Q==";
                String tableName = "authy";
                CloudStorageAccount account = CloudStorageAccount.Parse(dataConnectionString);
                // create the table client
                CloudTableClient tableClient = account.CreateCloudTableClient();
                // create the table if it doesn't exist
                CloudTable table = tableClient.GetTableReference(tableName);
            
                TableQuery query = new TableQuery().Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, User.Identity.Name));
                String AuthyUserID = " ";
              
                foreach (var entity in table.ExecuteQuery(query))
                {
                    AuthyUserID = entity.RowKey;
                }
     
                VerifyTokenResult result = client.VerifyToken(AuthyUserID, TokenBox.Text, false);

                if (result.Status.Equals(AuthyStatus.Success))
                {
                    Response.Redirect("~/");
                }
                else
                {
                    ModelState.AddModelError("NewPassword", result.Status.ToString());
                }
            }
        }

        protected void sendSMSToken_Click(object sender, EventArgs e)
        {
           
            if (IsValid)
            {
                AuthyClient client = new AuthyClient("9d757c049978d32651d0e11e801b36f2", test: false);

                // for a real storage account:
                String dataConnectionString = "DefaultEndpointsProtocol=https;AccountName=aliciaauthy;AccountKey=UihKsy9AYk9R/UFMhpnxs9Ju459H+BVaUROJ5SJuGL7M2y8ILV8QwmeEK1gw+ga+AYwcF9nMjq5VPsztoGHT1Q==";
                String tableName = "authy";
                CloudStorageAccount account = CloudStorageAccount.Parse(dataConnectionString);
                // create the table client
                CloudTableClient tableClient = account.CreateCloudTableClient();
                // create the table if it doesn't exist
                CloudTable table = tableClient.GetTableReference(tableName);
            
                TableQuery query = new TableQuery().Where(TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, User.Identity.Name));
                String AuthyUserID = " ";

                foreach (var entity in table.ExecuteQuery(query))
                {
                    AuthyUserID = entity.RowKey;
                }
                client.SendSms(AuthyUserID);
     
                //VerifyTokenResult result = client.VerifyToken(AuthyUserID, TokenBox.Text, false);

                //if (result.Status.Equals(AuthyStatus.Success))
                //{
                //    Response.Redirect("~/");
                //}
                //else
                //{
                //    ModelState.AddModelError("NewPassword", result.Status.ToString());
                //}
            }
        }

        //public IEnumerable<OpenAuthAccountData> GetExternalLogins()
        //{
        //    var accounts = OpenAuth.GetAccountsForUser(User.Identity.Name);
        //    CanRemoveExternalLogins = CanRemoveExternalLogins || accounts.Count() > 1;
        //    return accounts;
        //}

        //public void RemoveExternalLogin(string providerName, string providerUserId)
        //{
        //    var m = OpenAuth.DeleteAccount(User.Identity.Name, providerName, providerUserId)
        //        ? "?m=RemoveLoginSuccess"
        //        : String.Empty;
        //    Response.Redirect("~/Account/Manage" + m);
        //}


        protected static string ConvertToDisplayDateTime(DateTime? utcDateTime)
        {
            // You can change this method to convert the UTC date time into the desired display
            // offset and format. Here we're converting it to the server timezone and formatting
            // as a short date and a long time string, using the current thread culture.
            return utcDateTime.HasValue ? utcDateTime.Value.ToLocalTime().ToString("G") : "[never]";
        }
    }
}